<template>
  <div class="roles-container">
    <div class="page-header">
      <h2>角色管理</h2>
      <el-button type="primary" @click="handleAddRole" size="default">
        <el-icon><component is="i-plus" /></el-icon>
        添加角色
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" class="search-form">
        <el-form-item label="角色名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入角色名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" size="small">
            <el-icon><component is="i-search" /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch" size="small">
            <el-icon><component is="i-refresh-left" /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 角色表格 -->
    <el-card class="roles-table-card" shadow="hover">
      <el-table
        :data="rolesData"
        style="width: 100%"
        border
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="id" label="ID" width="80" fixed />
        <el-table-column prop="name" label="角色名称" width="180" />
        <el-table-column prop="description" label="角色描述" />
        <el-table-column prop="level" label="角色级别" width="120" />
        <el-table-column prop="permissions_count" label="权限数量" width="120">
          <template #default="{ row }">
            <el-tag size="small" type="info">{{
              row.permissions_count || 0
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEditRole(row)"
              :disabled="editingId === row.id"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteRole(row)"
              :disabled="deletingId === row.id || row.name === '超级管理员'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加角色' : '编辑角色'"
      width="700px"
      destroy-on-close
    >
      <el-form
        :model="roleForm"
        :rules="roleRules"
        ref="roleFormRef"
        label-width="100px"
        class="role-form"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="roleForm.name"
            placeholder="请输入角色名称"
            :disabled="dialogType === 'edit' && roleForm.name === '超级管理员'"
          />
        </el-form-item>

        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            placeholder="请输入角色描述"
            type="textarea"
            rows="3"
          />
        </el-form-item>

        <el-form-item label="角色级别" prop="level" v-if="dialogType === 'add'">
          <el-input
            v-model.number="roleForm.level"
            placeholder="请输入角色级别（数字）"
            type="number"
            min="0"
          />
          <div class="form-tip">
            预定义角色：超级管理员(500)、任务管理员(400)、飞手(300)、观测员(200)、审计员(100)
          </div>
        </el-form-item>

        <el-form-item label="权限选择">
          <el-checkbox-group
            v-model="roleForm.permission_ids"
            class="permission-checkbox-group"
          >
            <el-checkbox
              v-for="permission in permissions"
              :key="permission.id"
              :label="permission.id"
              class="permission-checkbox"
            >
              {{ permission.name }} - {{ permission.description }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="dialogLoading"
          >
            {{ dialogLoading ? "提交中..." : "确定" }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import service from '@/utils/request';

export default {
  name: "Roles",
  setup() {
    const loading = ref(false);
    const dialogVisible = ref(false);
    const dialogType = ref("add"); // 'add' or 'edit'
    const dialogLoading = ref(false);
    const roleFormRef = ref(null);
    const editingId = ref(null);
    const deletingId = ref(null);

    // 搜索表单
    const searchForm = reactive({
      name: "",
    });

    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0,
    });

    // 角色表单
    const roleForm = reactive({
      id: "",
      name: "",
      description: "",
      level: 0,
      permission_ids: [],
    });

    // 表单验证规则
    const roleRules = {
      name: [
        { required: true, message: "请输入角色名称", trigger: "blur" },
        {
          min: 2,
          max: 50,
          message: "角色名称长度在 2 到 50 个字符",
          trigger: "blur",
        },
      ],
      level: [
        { type: "number", message: "角色级别必须是数字", trigger: "blur" },
        { min: 0, message: "角色级别不能小于0", trigger: "blur" },
      ],
    };

    // 权限数据
    const permissions = ref([]);

    // 角色数据
    const rolesData = ref([]);

    // 初始化
    onMounted(() => {
      fetchPermissions();
      fetchRoles();
    });

    // 获取权限列表
    const fetchPermissions = async () => {
      try {
        const response = await service.get("/permissions", {
      params: {
        page: 1,
        page_size: 100
      }
    });

        if (response.code === 200) {
          permissions.value = response.data.items || [];
        } else {
          ElMessage.error(response.message || "获取权限列表失败");
        }
      } catch (error) {
        console.error("获取权限列表失败:", error);
        ElMessage.error(error.response?.message || "获取权限列表失败");
      }
    };

    // 获取角色列表
    const fetchRoles = async () => {
      loading.value = true;
      try {
        const response = await service.get("/roles", {
          params: {
            page: pagination.currentPage,
            page_size: pagination.pageSize,
            name: searchForm.name || undefined,
          }
        });

        if (response.code === 200) {
          // 处理角色数据，添加权限数量
          rolesData.value = response.data.items.map((role) => ({
            ...role,
            permissions_count: role.permissions ? role.permissions.length : 0,
          }));
          pagination.total = response.data.total;
        } else {
          ElMessage.error(response.message || "获取角色列表失败");
        }
      } catch (error) {
        console.error("获取角色列表失败:", error);
        ElMessage.error(error.response?.message || "获取角色列表失败");
      } finally {
        loading.value = false;
      }
    };

    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1;
      fetchRoles();
    };

    // 重置搜索
    const resetSearch = () => {
      searchForm.name = "";
      pagination.currentPage = 1;
      fetchRoles();
    };

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      fetchRoles();
    };

    const handleCurrentChange = (current) => {
      pagination.currentPage = current;
      fetchRoles();
    };

    // 打开添加角色对话框
    const handleAddRole = () => {
      dialogType.value = "add";
      resetRoleForm();
      dialogVisible.value = true;
    };

    // 打开编辑角色对话框
    const handleEditRole = async (row) => {
      dialogType.value = "edit";
      editingId.value = row.id;

      try {
        // 获取角色详情（包含权限信息）
        const response = await service.get(`/roles/${row.id}`);

        if (response.code === 200) {
          const roleData = response.data;
          // 填充表单数据
          roleForm.id = roleData.id;
          roleForm.name = roleData.name;
          roleForm.description = roleData.description;
          roleForm.level = roleData.level;
          roleForm.permission_ids = roleData.permissions
            ? roleData.permissions.map((p) => p.id)
            : [];
          dialogVisible.value = true;
        } else {
          ElMessage.error(response.message || "获取角色详情失败");
        }
      } catch (error) {
        console.error("获取角色详情失败:", error);
        ElMessage.error(error.response?.message || "获取角色详情失败");
      }
    };

    // 删除角色
    const handleDeleteRole = (row) => {
      if (row.name === "超级管理员") {
        ElMessage.warning("超级管理员角色不能删除");
        return;
      }

      ElMessageBox.confirm(`确定要删除角色「${row.name}」吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          deletingId.value = row.id;
          try {
            const response = await service.delete(`/roles/${row.id}`);

            if (response.data.code === 200) {
              ElMessage.success("删除成功");
              fetchRoles();
            } else {
              ElMessage.error(response.data.message || "删除角色失败");
            }
          } catch (error) {
            console.error("删除角色失败:", error);
            ElMessage.error(error.response?.data?.message || "删除失败");
          } finally {
            deletingId.value = null;
          }
        })
        .catch(() => {
          // 取消删除
          ElMessage.info("已取消删除");
        });
    };

    // 重置角色表单
    const resetRoleForm = () => {
      if (roleFormRef.value) {
        roleFormRef.value.resetFields();
      }
      Object.assign(roleForm, {
        id: "",
        name: "",
        description: "",
        level: 0,
        permission_ids: [],
      });
    };

    // 提交表单
    const handleSubmit = async () => {
      roleFormRef.value.validate(async (valid) => {
        if (valid) {
          dialogLoading.value = true;
          try {
            if (dialogType.value === "add") {
              // 添加角色
              const response = await service.post(
                "/roles",
                {
                  name: roleForm.name,
                  description: roleForm.description,
                  level: roleForm.level,
                  permission_ids: roleForm.permission_ids,
                }
              );

              if (response.data.code === 200) {
                ElMessage.success("添加成功");
                dialogVisible.value = false;
                fetchRoles();
              } else {
                ElMessage.error(response.data.message || "添加角色失败");
              }
            } else {
              // 更新角色
              const response = await service.put(
                `/roles/${editingId.value}`,
                {
                  name: roleForm.name,
                  description: roleForm.description,
                  permission_ids: roleForm.permission_ids,
                }
              );

              if (response.data.code === 200) {
                ElMessage.success("更新成功");
                dialogVisible.value = false;
                fetchRoles();
              } else {
                ElMessage.error(response.data.message || "更新角色失败");
              }
            }
          } catch (error) {
            console.error("操作角色失败:", error);
            ElMessage.error(error.response?.data?.message || "操作失败");
          } finally {
            dialogLoading.value = false;
            editingId.value = null;
          }
        }
      });
    };

    return {
      loading,
      dialogVisible,
      dialogType,
      dialogLoading,
      roleFormRef,
      searchForm,
      pagination,
      roleForm,
      roleRules,
      permissions,
      rolesData,
      editingId,
      deletingId,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleAddRole,
      handleEditRole,
      handleDeleteRole,
      handleSubmit,
    };
  },
};
</script>

<style scoped>
.roles-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: end;
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.roles-table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.role-form .el-form-item {
  margin-bottom: 20px;
}

.permission-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.permission-checkbox {
  white-space: normal;
  line-height: 1.5;
}

.form-tip {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
}
</style>
